package collectors.people.services;

import java.util.List;
import java.util.concurrent.Callable;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;

import play.libs.Akka;
import play.libs.F.Promise;
import collectors.people.models.PeopleUser;
import collectors.people.util.Config;

import com.googlecode.batchfb.Batcher;
import com.googlecode.batchfb.FacebookBatcher;
import com.googlecode.batchfb.Later;

public class FacebookQueryService {

	public static Promise<JsonNode> getUserData(Long peopleUserId) {
		PeopleUser user = PeopleUser.find.byId(peopleUserId);
		return getUserData(user.fbdata.accessToken);
	}
	
	public static Promise<JsonNode> getUserData(String accessToken) {
		Batcher batcher = new FacebookBatcher(accessToken);
		final Later<JsonNode> userdata = batcher.graph("me");
		return Akka.future(new Callable<JsonNode>() {
			@Override
			public JsonNode call() throws Exception {
				return userdata.get();
			}
		});
	}
	
	public static Promise<List<PeopleUser.FacebookData>> searchUserModel(Long peopleUserId, String query) {
		PeopleUser user = PeopleUser.find.byId(peopleUserId);
		return searchUserModel(query, user.fbdata.accessToken);
	}
	
	// returns users which name contains query
	public static Promise<List<PeopleUser.FacebookData>> searchUserModel(String query, String accessToken) {
		Batcher batcher = new FacebookBatcher(accessToken);
		String queryTemplate = Config.get().userfbquery;
		final Later<List<PeopleUser.FacebookData>> users = batcher.query(
				queryTemplate.replace("$NAME$", query.toLowerCase()), PeopleUser.FacebookData.class);
		return Akka.future(new Callable<List<PeopleUser.FacebookData>>() {
			@Override
			public List<PeopleUser.FacebookData> call() throws Exception {
				return users.get();
			}
		});
	}
	
	//TODO check how to limit number of results
	public static Promise<ArrayNode> searchUserJSON(String query, String accessToken) {
		Batcher batcher = new FacebookBatcher(accessToken);
		String queryTemplate = Config.get().userfbquery;
		final Later<ArrayNode> users = batcher.query(
				queryTemplate.replace("$NAME$", query.toLowerCase()));
		return Akka.future(new Callable<ArrayNode>() {
			@Override
			public ArrayNode call() throws Exception {
				return users.get();
			}
		});
	}

}
